﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI.Xaml.Controls;
using Daabli;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace StoreApp
{
    public enum Master
    {
        Tigress, Monkey, Mantis, Viper, Crane
    };

    public sealed partial class MainPage : Page
    {
        #region Helpers
        private static async Task<Stream> GetFileStreamAsync(string filename)
        {
            var uri = new Uri("ms-appx:///" + filename);

            var file = await StorageFile.GetFileFromApplicationUriAsync(uri).AsTask().ConfigureAwait(false);
            var stream = await file.OpenStreamForReadAsync().ConfigureAwait(false);

            return stream;
        }
        private static Stream GetFileStream(string filename)
        {
            var task = GetFileStreamAsync(filename);
            task.Wait();

            return task.Result;
        }
        public static bool LoadFile(Reader r, string filename)
        {
            if (string.IsNullOrEmpty(filename))
            {
                r.Log.Write(MessageType.InvalidArgument, "filename cannot be empty");
                return false;
            }

            Stream stream = null;
            Reader.NoThrowAction(() => { stream = GetFileStream(filename); });

            if (stream == null)
            {
                r.Log.Write(MessageType.Error, "failed to open file '{0}'", filename);
                return false;
            }

            using (stream)
                return r.FromStream(stream);
        }
        private static string StringFrom<T>(List<T> list)
        {
            if (list.Count <= 0)
                return string.Empty;

            var result = new StringBuilder();

            result.Append(list[0]);
            for (int i = 1; i < list.Count; ++i)
            {
                result.Append(", ");
                result.Append(list[i]);
            }

            return result.ToString();
        }
        #endregion

        public MainPage()
        {
            this.InitializeComponent();

            // create a reader
            var r = new DefaultReader();

            // load data from file
            if (LoadFile(r, "data.txt"))
            {
                bool isSmiling = false;
                char weaponClass = 'A';
                float speed = 0;
                int pixelCount = 0;
                string desc = null;
                float agility = 0;
                Master master = Master.Tigress;
                List<string> tags = new List<string>();
                Creature creature = null;
                List<string> userNames = new List<string>();
                string currentUser = null;

                // register custom type names
                r.RegisterTypeName<Master>();
                r.RegisterTypeName<Wolf>();

                // read data
                bool result =
                    r.Read("isSmiling", ref isSmiling) &&
                    r.Read("weaponClass", ref weaponClass) &&
                    r.Read("speed", ref speed) &&
                    r.Read("pixelCount", ref pixelCount) &&
                    r.Read("desc", ref desc) &&
                    r.Read("agility", ref agility, 1.2f) &&
                    r.Read("master", ref master) &&
                    r.Read("tags", ref tags) &&
                    r.Read("creature", ref creature) &&
                    r.Read("userNames", ref userNames) &&
                    r.Read("currentUser", ref currentUser);

                // show data
                if (result)
                {
                    _tbIsSmiling.Text = isSmiling.ToString();
                    _tbWeaponClass.Text = weaponClass.ToString();
                    _tbSpeed.Text = speed.ToString();
                    _tbPixelCount.Text = pixelCount.ToString();
                    _tbDesc.Text = desc;
                    _tbAgility.Text = agility.ToString();
                    _tbMaster.Text = master.ToString();
                    _tbTags.Text = StringFrom(tags);
                    _tbCreature.Text = creature.ToString();
                    _tbUserNames.Text = StringFrom(userNames);
                    _tbCurrentUser.Text = currentUser;
                }
            }

            // show log
            var resultText = new StringBuilder();
            {
                resultText.Append("log: ");

                var log = r.Log.ToString();
                if (!string.IsNullOrEmpty(log))
                {
                    resultText.AppendLine();
                    resultText.Append(log);
                }
                else
                    resultText.Append("empty");
            }
            _tbResult.Text = resultText.ToString();
        }
    }
}
